//
//  JTMeFooterView.m
//  百思不得姐
//
//  Created by Robin Zhang on 2016/12/23.
//  Copyright © 2016年 BeiJingWangDianJieTong. All rights reserved.
//

#import "JTMeFooterView.h"
#import "JTMeSquare.h"
#import "JTHTTPSessionManager.h"
#import <MJExtension.h>
#import "JTMeSquareButton.h"
#import "JTWebViewController.h"
#import <SafariServices/SafariServices.h>
#import "JTProgressHUD.h"

@interface JTMeFooterView ()

@end

@implementation JTMeFooterView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        // 参数
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:@"square" forKey:@"a"];
        [params setObject:@"topic" forKey:@"c"];
        
        // 请求
        [[JTHTTPSessionManager manager] GET:JTCommonURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
            
//            JTLog(@"%@", responseObject);
            
            // 字典数组 -> 模型数组
            NSArray<JTMeSquare *> *squares = [JTMeSquare mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"]];
            
            /* 新增：去除重复模型 */
            NSMutableArray<JTMeSquare *> *array = [NSMutableArray array];
            for (JTMeSquare *square in squares) {
                
                BOOL contained = NO;
                
                for (JTMeSquare *subSquare in array) {
                    
                    if ([square.name isEqualToString:subSquare.name]) {
                        
                        contained = YES;
                        break;
                    }
                }
                
                if (!contained) [array addObject:square];
            }
            squares = array;
            
            // 根据模型数据创建相应的控件
            [self createSqueares:squares];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            JTLog(@"请求失败 - %@", error);
            
            [JTProgressHUD showErrorWithError:error];
        }];
    }
    return self;
}

/** 
 根据模型数据创建相应的控件
 */
- (void)createSqueares:(NSArray<JTMeSquare *> *)squares {
    
    // 1.方块个数
    NSUInteger count = squares.count;
    
    // 2.方块的尺寸
    NSInteger maxColumnsCount = 4; // 1行最大列数
    CGFloat buttonWidth = self.jt_width / maxColumnsCount;
    CGFloat buttonHeight = buttonWidth;
    
    // 补全最后一行
    // 余数
    NSUInteger left = count % maxColumnsCount;
    
    // 3.添加按钮
    for (NSUInteger i = 0; i < count + (left > 0)?(maxColumnsCount - left):0; i++) {
        
        // 创建按钮
        JTMeSquareButton *button = [JTMeSquareButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        
        // 设置frame
        [button setJt_x:(i % maxColumnsCount) * buttonWidth];
        [button setJt_y:(i / maxColumnsCount) * buttonWidth];
        [button setJt_width:buttonWidth];
        [button setJt_height:buttonHeight];
        
        // 设置数据
        if (i < count) [button setSquare:[squares objectAtIndex:i]];
    }
    
    // 总行数:公式-NSUinteger rowsCount = (总数 + 每一行最多显示的数量 - 1) / 每一行最多显示的数量
//    NSUInteger rowsCount = count / maxColumnsCount + ((count % maxColumnsCount)?1:0);
//    NSUInteger rowsCount = (count + maxColumnsCount - 1) / maxColumnsCount;
//    [self setJt_height:rowsCount * buttonHeight];
    
    // 设置footer的高度 == 最后一个按钮的bottom(最大Y值)
    [self setJt_height:self.subviews.lastObject.jt_bottom];
    
    // 设置tableView的contentSize
    UITableView *tableView = (UITableView *)self.superview;
    [tableView reloadData];
}

- (void)buttonClick:(JTMeSquareButton *)button {
    
    if (button.square) {
        
        NSString *url = button.square.url;
        JTLog(@"%@", url);
        
        // 利用WebView加载url即可
        if ([url hasPrefix:@"http"]) { // 以XX为前缀
            
            // 利用SFSafariViewController显示网页 NS_CLASS_AVAILABLE_IOS(9_0)
//            SFSafariViewController *webViewController = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:url]];
//            [self.window.rootViewController presentViewController:webViewController animated:YES completion:nil];
            
            // 显示JTWebViewController
            JTWebViewController *webViewController = [[JTWebViewController alloc] init];
            [webViewController setUrl:url];
            [webViewController.navigationItem setTitle:button.currentTitle];
            
            // 获得“我”模块对应的导航控制器并跳转
            [((UITabBarController *)self.window.rootViewController).selectedViewController pushViewController:webViewController animated:YES];
        }
        else if ([url hasPrefix:@"mod"]) { //另行处理
            
            if ([url hasSuffix:@"BDJ_To_Check"]) {
                
                JTLog(@"跳转到[审帖]界面");
            }
            else if ([url hasSuffix:@"BDJ_To_RecentHot"]) {
                
                JTLog(@"跳转到[每日排行]界面");
            }
            else {
                
                JTLog(@"跳转到其他界面");
            }
        }
        else {
            
            JTLog(@"不是http或者mod协议的");
        }
    }
}

@end
